package edu.scau.pos.service;

import edu.scau.core.util.ServletUtils;
import edu.scau.pos.domain.SaleLineItem;
import edu.scau.pos.mapper.SaleLineItemMapper;
import edu.scau.pos.vo.SaleItemVo;
import edu.scau.system.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
@Service
public class SaleLineItemServiceImpl implements SaleLineItemService{
    @Autowired
    private SaleLineItemMapper saleLineItemMapper;
    @Autowired
    private TokenService tokenService;
    @Override
    public List<SaleItemVo> listAll() {
        return saleLineItemMapper.listAll();
    }

    @Override
    public List<SaleItemVo> listByOrderId(String orderId) {
        return saleLineItemMapper.listByOrderId(orderId);
    }

    @Override
    public int updateSalelineitem(SaleLineItem salelineitem) {
        salelineitem.setUpdateBy(tokenService.getLoginUser(ServletUtils.getRequest()).getUsername());
        salelineitem.setUpdateTime(new Date());
        return saleLineItemMapper.updateSalelineitem(salelineitem);
    }

    @Override
    public int deleteSalelineitemByOrderId(String orderId) {
        return saleLineItemMapper.deleteSalelineitemByOrderId(orderId);
    }

    @Override
    public int insertSalelineitem(SaleLineItem salelineitem) {
        salelineitem.setCreateBy(tokenService.getLoginUser(ServletUtils.getRequest()).getUsername());
        salelineitem.setCreateTime(new Date());
        salelineitem.setIsDeleted(0);
        return saleLineItemMapper.insertSalelineitem(salelineitem);
    }

    @Override
    public int insertBatch(List<SaleLineItem> saleLineItemList) {
        String createBy = tokenService.getLoginUser(ServletUtils.getRequest()).getUsername();
        Date createTime = new Date();
        saleLineItemList.forEach(item -> {
            item.setCreateBy(createBy);
            item.setCreateTime(createTime);
            item.setIsDeleted(0);
        });
        return saleLineItemMapper.insertBatch(saleLineItemList);
    }

    @Override
    @Transactional
    public int updateBatch(List<SaleLineItem> saleLineItems) {
        Date updateTime = new Date();
        String updateBy = tokenService.getLoginUser(ServletUtils.getRequest()).getUsername();
        saleLineItems.forEach(item -> {
            item.setUpdateBy(updateBy);
            item.setUpdateTime(updateTime);
        });
        return saleLineItemMapper.updateBatch(saleLineItems);
    }
}
